﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace CusCheckedListBox
{
    public class CoolCheckedListBox : CheckedListBox
    {
        Image image = new Bitmap(CusCheckedListBox.Properties.Resources.compose_privatebutton_background);
        CoolItemCollection _items = null;
        public CoolCheckedListBox():base()
        {
            _items = new CoolItemCollection(this);
            this.SetStyle(ControlStyles.UserPaint, false);
            this.SetStyle(ControlStyles.DoubleBuffer, true);// 双缓冲
            this.SetStyle(ControlStyles.ResizeRedraw, true);//调整大小时重绘
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);// 双缓冲            
            //this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }
        
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            base.OnDrawItem(e);//调用父类，完成CheckBox的添加绘制过程，此类存在的价值

            int index = e.Index;
            if (index < Items.Count)    //判断添加的原因，可以自己验证
            {
                Graphics g = e.Graphics;

                Rectangle bounds = this.GetItemRectangle(index);//取得当前Item的区域Rectangle

                //清空重绘区域
                g.Clip = new Region(new Rectangle(bounds.X + 15, bounds.Y, bounds.Width, bounds.Height));//Rectangle构造函数中的参数指定一定要是bounds.X或bounds.Y的相对值，否则太纠结
                g.FillRegion(Brushes.White, g.Clip);

                //图片
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;    //插入模式
                g.DrawImage(image, new Rectangle(bounds.X + 15, bounds.Y, image.Size.Width * 2 / 3, image.Size.Height * 2 / 3));

                //文本
                Color textColor = this.GetItemCheckState(e.Index) == CheckState.Unchecked ? Color.Maroon : (this.GetItemCheckState(e.Index) == CheckState.Checked ? Color.Olive : Color.LimeGreen);
                g.DrawString(((CoolItem)Items[index]).ToString(), new Font("微软雅黑", 9), new SolidBrush(textColor), bounds.Left + 33, bounds.Top);
            }
        }
        protected override void OnMeasureItem(MeasureItemEventArgs e)
        {
            base.OnMeasureItem(e);
            e.ItemHeight = 30;
        }
        
    }
}
